package com.zb.service.imp.middleware;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zb.dao.ext.charger.OmsChargerChargeBillRecordDao;
import com.zb.dao.ext.charger.OmsChargerDao;
import com.zb.entity.base.JsonCommon;
import com.zb.entity.charger.OmsCharger;
import com.zb.entity.charger.OmsChargerChargeBillRecord;
import com.zb.service.imp.middleware.instruction.Ev3c2Instructions;
import com.zb.service.imp.middleware.instruction.Ev3cInstructions;
import com.zb.service.imp.middleware.instruction.InstructionType;
import com.zb.service.imp.middleware.notify.app.NotifyAppServer;
import com.zb.service.middleware.AnalysisService;
import com.zb.service.middleware.EncapsulationService;
import com.zb.service.middleware.LoginService;
import com.zb.service.middleware.MessageService;
import com.zb.service.middleware.OmsBespeakService;
import com.zb.service.middleware.OmsChargeService;
import com.zb.service.middleware.SetService;
import com.zb.service.middleware.UploadDataService;
import com.zb.service.sys.ChargerUploadService;
import com.zb.tcp.rpc.as.SystemAppServerRpcClient;
import com.zb.tcp.rpc.as.client.constant.AppServerConstant;
import com.zb.tcp.rpc.as.client.entity.AppChargeNotifyParam;
import com.zb.tcp.rpc.ms.SystemMasterServerRpcClient;
import com.zb.tcp.rpc.ms.client.entity.MasterQueryIdentityCardVO;
import com.zb.tcp.rpc.ms.client.entity.MasterQueryOfflineCardVO;
import com.zb.tcp.socket.LongConnectionSendMsgImpl;
import com.zb.tcp.socket.MessageFuture;
import com.zb.tcp.socket.SendMsg;
import com.zb.tcp.socket.exception.CreateConnectionFailException;
import com.zb.tcp.socket.exception.DuplicateInstructionException;
import com.zb.tcp.socket.exception.RetryFailException;
import com.zb.tcp.socket.exception.SendMsgTimeOutException;
import com.zb.util.CardUtils;
import com.zb.util.OmsConstant;
import com.zb.util.StringUtil;
import com.zb.util.OmsConstant.CardTypeEnum;
@Service
public class Ev3cMessageServiceImpl implements MessageService{

	private static Log log = LogFactory.getLog(Ev3cMessageServiceImpl.class);
//	@Resource(name = "dzTcpShortConnectionClient")
//	ISendMsg sendMsg ;
//	DzTcpLongConnectionClient
	@Resource(name = "longConnectionSendMsgImpl")
	SendMsg sendMsg;
	@Resource(name = "ev3cAnalysisServiceImpl")
	AnalysisService ev3cAnalysisService;
	@Resource(name = "ev3cEncapsulationServiceImpl")
	EncapsulationService ev3cEncapsulationService;
	@Resource(name = "ev3c2AnalysisServiceImpl")
	AnalysisService ev3c2AnalysisService;
	@Resource(name = "ev3c2EncapsulationServiceImpl")
	EncapsulationService ev3c2EncapsulationService;
	@Autowired
	LoginService loginService;	
	@Autowired
	ChargerUploadService chargerUploadService;
	@Autowired
	UploadDataService uploadDataService;
	@Autowired
	OmsChargeService omsChargeService;
	@Autowired
	OmsBespeakService omsBespeakService;
	@Autowired
	SetService setService;
	@Autowired
	OmsChargerDao omsChargerDao;
	@Resource
	OmsChargerChargeBillRecordDao omsChargerChargeBillRecordDao;
//	@Resource
//	SystemAppServerRpcClient systemAppServerRpcClient;
	
//	@Autowired
//	private SystemMasterServerRpcClient systemMasterServerRpcClient;
//	@Autowired
//	SendShortClientService sendShortClientService;
//	@Resource(name = "ev3cSendCallBack")
//	SendCallBack ev3cSendCallBack;
	
	String ev3c_magHeader,ev3c_magBody,ev3c_frameCode;
//	private Channel ccc;
	public Ev3cMessageServiceImpl()
	{
		log.debug("Constructor");
//		DzTcpLongConnectionClient longconn = new DzTcpLongConnectionClient();
//		longconn.registerReceiveListener(new ReceiveEventListenerImpl());
//		this.sendMsg = longconn;
	}
	
	@Override
	public String send(String data) {
		return null;
	}
	//短连接发送给中间件的格式是   报文
	//长连接发送给中间件的格式是  data=报文
	@SuppressWarnings({ "rawtypes" })
	@Override
	public JsonCommon receive(Map<String, String> map,Channel channel) throws Exception
	{
		log.debug(this.toString());
//	public JsonCommon receive(String msg,Channel channel) {
		JsonCommon json = new JsonCommon();
//		Map<String, String> map= StringUtil.string2JSONObject(msg);
		String protocol_version = map.get("protocol_version");
		switch(protocol_version){
		case "0101":
		case "0102":
		case "0103":
			json = ev3c01receive(map,channel);
			break;
		default:
			break;
		}
		
		return json;
	}


	@SuppressWarnings("rawtypes")
	private JsonCommon ev3c01receive(Map<String, String> map, Channel channel) throws Exception
	{
		JsonCommon json = new JsonCommon();
		String data = map.get("data");
		ev3c_frameCode = data.substring(34, 36);

		Ev3cInstructions instruction = Ev3cInstructions.parse(ev3c_frameCode);
		if (instruction.type() == InstructionType.ReplyByCharger)
		{
			String replyFor = map.get("replyFor");
			MessageFuture future = null;
			if (replyFor != null)
			{
				future = LongConnectionSendMsgImpl.getMessageFutureMap().remove(replyFor);
				if (future != null)
				{
					String responseCode = data.substring(8, 14);
					if (!responseCode.equals(OmsConstant.MsgResponseCodeEnum.Normal.value()))
						future.setFailure(responseCode);
					else
						future.setSuccess(data);
				}
			}
		}

		switch(ev3c_frameCode){
		case "A1"://6.1.1 注册签到
			ev3c_frameCode = "A2";
			json = chargerLogin(map,channel);
			break;
		case "A3"://6.1.2	签退
			ev3c_frameCode = "A4";
			json = chargerLogout(map,channel);
			break;
		case "75"://6.4.1	刷卡请求
			ev3c_frameCode = "76";
			json = requestPayByCard(map,channel);
			break;
		case "51"://6.5.1	心跳报文
			ev3c_frameCode = "52";
			json = uploadHeart(map,channel);
			break;
		case "53"://6.5.2	主动遥变上传
			ev3c_frameCode = "59";
			json = uploadChange(map,channel);
			break;
		case "5A"://6.5.3	固件更新状态上传
			ev3c_frameCode = "5B";
			json = uploadFirmwareStatus(map,channel);
			break;
		case "54"://6.5.4	账单主动上传
			ev3c_frameCode = "55";
			json = uploadBill(map,channel);
			break;
			//控制类
		case "11"://充电  服务器回复 – 0x56 1.3报文中服务器 下发  -  电桩回复  - 服务器 回复
			ev3c_frameCode = "56";
			json = startChargeReturn(map,channel);
			String userCard = data.substring(54, 74);  //用户卡号
//			String[] arr = json.getCode().split(":");
//			String code = arr[0];
//			log.debug(json);
//			if (code.equals("200") && CardUtils.generateCardType(userCard).equals(CardTypeEnum.OnlineApp)) { // App卡
//				String notifyFlag = arr[1];
//				log.debug(notifyFlag);
//				if (notifyFlag.equals("1")) { // 1:预约充电, 2:刷卡充电
//					OmsCharger charger_query = new OmsCharger();
//					charger_query.setCharger_id(map.get("chargerId"));
//					charger_query.setPort_no(1);
//					OmsCharger charger = (OmsCharger) omsChargerDao.findOneExample(charger_query, null, null);
//					if (StringUtil.objectIsNull(charger)) {
//						log.error("Class:Ev3cMessageServiceImpl -> method:startChargeReturn -> result:Send to message fail(charger is null)!");
//					}
//
//					OmsChargerChargeBillRecord omsChargerChargeBillRecord = new OmsChargerChargeBillRecord();
//					OmsChargerChargeBillRecord omsChargerChargeBillRecord_query = new OmsChargerChargeBillRecord();
//					omsChargerChargeBillRecord_query.setUser_pay_card(userCard);
//					omsChargerChargeBillRecord_query.setCharger_id(map.get("chargerId"));
//					omsChargerChargeBillRecord_query.setStation_id(charger.getStation_id());
//					omsChargerChargeBillRecord_query.setStatus(1);
//					omsChargerChargeBillRecord_query.setPort_no(1);
//					omsChargerChargeBillRecord_query.setValid_flag(1);
//					omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "start_time", "desc");
//
//					if (StringUtil.objectIsNull(omsChargerChargeBillRecord)) {
//						log.error("Class:Ev3cMessageServiceImpl -> method:startChargeReturn -> result:Send to message fail(omsChargerChargeBillRecord is null)!");
//					} else {
//						log.info("notify app server");
//						NotifyAppServer.startChargeReturn(omsChargerChargeBillRecord.getMsg_charge_jrnl());
//					}
//				}
//			}
			break;
		case "13"://充电停止 服务器回复 – 0x57 1.3报文中服务器 下发  -  电桩回复  - 服务器 回复
			ev3c_frameCode = "57";
			json = stopChargeReturn(map,channel);
			userCard = data.substring(54, 74);  //用户卡号
			if (json.getCode().equals("200") && CardUtils.generateCardType(userCard).equals(CardTypeEnum.OnlineApp)) { // App卡
				OmsCharger charger_query = new OmsCharger();
				charger_query.setCharger_id(map.get("chargerId"));
				charger_query.setPort_no(1);
				OmsCharger charger = (OmsCharger) omsChargerDao.findOneExample(charger_query, null, null);
				if (StringUtil.objectIsNull(charger)) {
					log.error("Class:Ev3cMessageServiceImpl -> method:stopChargeReturn -> result:Send to message fail(charger is null)!");
				}
				
				OmsChargerChargeBillRecord omsChargerChargeBillRecord = new OmsChargerChargeBillRecord();
				OmsChargerChargeBillRecord omsChargerChargeBillRecord_query = new OmsChargerChargeBillRecord();
				omsChargerChargeBillRecord_query.setUser_pay_card(map.get("userCard"));
				omsChargerChargeBillRecord_query.setCharger_id(map.get("chargerId"));
				omsChargerChargeBillRecord_query.setStation_id(charger.getStation_id());
				// billRecord_query.setStatus(4); // 由于自动充满导致没有更新该状态
				omsChargerChargeBillRecord_query.setPort_no(1);
				omsChargerChargeBillRecord_query.setValid_flag(1);
				omsChargerChargeBillRecord_query.setOffline_is_pay(2);
				omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "start_time", "desc");
				
				if (StringUtil.objectIsNull(omsChargerChargeBillRecord)) {
					log.error("Class:Ev3cMessageServiceImpl -> method:stopChargeReturn -> result:Send to message fail(omsChargerChargeBillRecord is null)!");
				} else {
					NotifyAppServer.stopChargeReturn(omsChargerChargeBillRecord.getMsg_charge_jrnl());
				}
			}
			break;
		case "15"://预约 服务器回复   1.3报文中服务器 下发  -  电桩回复  
			bespeakReturn(map,channel);
			break;
		case "17"://预约取消    服务器回复 – 0x58 1.3报文中服务器 下发  -  电桩回复  - 服务器 回复
			ev3c_frameCode = "58";
			cancelBespeakReturn(map,channel);
			break;
		case "19"://电桩重启回复     1.3报文中服务器 下发  -  电桩回复  
			json = restartChargerReturn(map,channel);
			break;
		case "1B"://6.2.6固件更新指令  1.服务器下发 – 0x1A  2.充电桩回复 – 0x1B
			json = updateFirmwareReturn(map,channel);
			break;	
			//设置类
		case "31"://6.3.1查询硬件服务器IP   服务器下发   0x30  充电桩回复 – 0x31 
			json = findHardwareServerIpReturn(map,channel);
			break;
		case "33"://6.3.2设置硬件服务器IP  本指令暂时保留，按照规范，所有充电桩不能通过IP地址与硬件服务器通信，而应该使用DNS域名解析。
				  // 1.服务器下发 – 0x32  2.充电桩回复 – 0x33
			json = setHardwareServerIpReturn(map,channel);
			break;
		case "35"://6.3.3对时设置  1.服务器下发 – 0x34  2.充电桩回复 – 0x35
			json = setTimeReturn(map,channel);
			break;	
		case "37"://6.3.4电桩费率查询  1.服务器下发 – 0x36 2.充电桩回复 – 0x37
			json = findRateReturn(map,channel);
			break;
		case "39"://6.3.5电桩费率设置  1.服务器下发 – 0x38  2.充电桩回复 – 0x39
			json = setRateReturn(map,channel);
			break;
		case "78"://6.3.6电桩运营二维码设置  1.服务器下发 – 0x77  2.充电桩回复 – 0x78
			json = setQrCodeReturn(map,channel);
			break;
		case "3B"://6.3.7电桩白名单卡号查询   1.服务器下发 – 0x3A  2.充电桩回复 – 0x3B
			json = findWhiteListReturn(map,channel);
			break;
		case "3D"://6.3.8电桩白名单卡号设置  1.服务器下发 – 0x3C  2.充电桩回复 – 0x3D
			json = setWhiteListReturn(map,channel);
			break;
		case "3F"://6.3.9电桩参数查询/设置  1.服务器下发 – 0x3E  2.充电桩回复 – 0x3F
			json = setParamReturn(map,channel);
			break;
		//以下的指令，OMS均不用回复
		case "5C"://6.5.5	充电数据上传
			json = uploadChargeData(map);
			break;
		case "5D"://6.5.6	电池详情报文（可选）
			json = uploadBatteryData(map);
			break;//
		case "72"://2.充电桩回复遥测数据
			json = summonReturnUploadTelemetry(map);
			break;
		case "73"://3.充电桩回复遥信数据
			json = summonReturnUploadTelesignal(map);
			break;
		case "74"://4.充电桩回复遥脉数据
			json = summonReturnUploadPulse(map);
			break;
		default:
			break;
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon updateFirmwareReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.updateFirmwareReturn(map);
		//暂时是没有需要处理的业务，如果以后要处理，则只能存到 oms_charger_software_refresh[桩固件更新记录]中
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon setParamReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文，目前没有地方存这些数据 ，就只存在redis中
			map = ev3cAnalysisService.setParamReturn(map);
//			//处理业务 , omsChargeServiceImpl
//			json = setService.setParamReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("setParamReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon setWhiteListReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.setWhiteListReturn(map);
			//处理业务
			json = setService.setWhiteListReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("setWhiteListReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon findWhiteListReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.findWhiteListReturn(map);
			//处理业务 ,存入redis中 setServiceImpl
			json = setService.findWhiteListReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("findWhiteListReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon setQrCodeReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.setQrCodeReturn(map);
			//处理业务 
			json = setService.setQrCodeReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("bespeakReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon setRateReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.setRateReturn(map);
			//处理业务 ,处理业务 ,数据存入redis中  setServiceImpl
			json = setService.setRateReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("bespeakReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon findRateReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.findRateReturn(map);
			//处理业务 ,数据存入redis中
			json = setService.findRateReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("bespeakReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	//这个方法目前没有必要
	@SuppressWarnings("rawtypes")
	private JsonCommon setTimeReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.setTimeReturn(map);
		//处理业务 ,目前没有地方存这些数据 TODO setServiceImpl
		json = setService.setTimeReturn(map);
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon setHardwareServerIpReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.setHardwareServerIpReturn(map);
			//处理业务
			json = setService.setHardwareServerIpReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("setHardwareServerIpReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon findHardwareServerIpReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.findHardwareServerIpReturn(map);
			//处理业务
			json = setService.findHardwareServerIpReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("findHardwareServerIpReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon restartChargerReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.restartChargerReturn(map);
			//处理业务
			json = omsChargeService.restartChargerReturn(map);
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("bespeakReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private void bespeakReturn(Map<String, String> map, Channel channel) {
		try
		{
			//解析报文
			map = ev3cAnalysisService.bespeakReturn(map);
			//处理业务
			omsBespeakService.bespeakReturn(map);
		}
		catch (Exception e)
		{
			log.error(e.getMessage(), e);
			throw e;
		}
	}
	@SuppressWarnings("rawtypes")
	private void cancelBespeakReturn(Map<String, String> map, Channel channel) throws RetryFailException, CreateConnectionFailException
	{
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.cancelBespeakReturn(map);
			//处理业务,封装待发送报文
			omsBespeakService.cancelBespeakReturn(map);
//			String msg = json.getPojo().toString();
//			sendNoWait(msg);
//			sendMsg.send(msg, 0, null);
//			sendShortClientService.send(msg);
//			sendMsg.sendAsync(msg, map.get("chargerId"));
//			channel.write(msg);
//			Thread.sleep(5000);
//			channel.close();
		}  catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;

		}
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon stopChargeReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.stopChargeReturn(map);
			//处理业务,封装待发送报文
			json = omsChargeService.stopChargeReturn(map);
			String msg = json.getPojo().toString();
//			sendNoWait(msg);
//			sendMsg.send(msg, 0, null);
//			sendShortClientService.send(msg);
			sendMsg.sendAsync(msg, map.get("chargerId"));
//			channel.write(msg);
//			Thread.sleep(5000);
//			channel.close();
//			json.setCode("200");
//			json.setMsg("chargerLogin return received");
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("stopChargeReturn fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon startChargeReturn(Map<String, String> map, Channel channel) {
		JsonCommon json = new JsonCommon();
		try {
			//解析报文
			map = ev3cAnalysisService.startChargeReturn(map);
			//处理业务,封装待发送报文
			json = omsChargeService.startChargeReturn(map);
			String msg = json.getPojo().toString();
//			sendNoWait(msg);
//			sendMsg.send(msg, 0, null);
//			sendShortClientService.send(msg);
			sendMsg.sendAsync(msg, map.get("chargerId"));
//			channel.write(msg);
//			Thread.sleep(5000);
//			channel.close();
//			json.setCode("200");
//			json.setMsg("chargerLogin return received");
		}  catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("startCharge return fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
			return json;
	}

	@SuppressWarnings("rawtypes")
	private JsonCommon chargerLogin(Map<String, String> map,Channel channel) {
		JsonCommon json = loginService.evCharLogin(map);
		String msg = json.getPojo().toString();
		// StringUtil.complement参数解释如下:1.对发送的整个文本求长度(data=xxx.....), 2.返回补位结果的长度)
		msg = "data=".concat(StringUtil.complement(String.valueOf(msg.length() + 9), 4)).concat(msg);
		try {
//			sendNoWait(msg);
//			sendMsg.send(msg, 0, null);
//			sendShortClientService.send(msg);
			//sendMsg.sendAsync(msg, map.get("chargerId"));
			channel.write(msg);
//			Thread.sleep(5000);
//			channel.close();
			json.setCode("200");
			json.setMsg("chargerLogin return received");
		}  catch (Exception e) {
			log.error(e.getMessage(), e);
			json.setCode("10303200");
			json.setMsg("chargerLogin return fail sendLongClientService Exception：" + e.getMessage());
//			e.printStackTrace();
		}
		return json;
	}	
	
	@SuppressWarnings("rawtypes")
	private JsonCommon chargerLogout(Map<String, String> map,Channel channel) {
		JsonCommon json = loginService.dzLoginOut(map);
		String msg = json.getPojo().toString();
		try {
//			sendShortClientService.send(msg);
//			sendMsg.send(msg, 0, null);
			sendMsg.sendAsync(msg, map.get("chargerId"));
//			channel.write(msg);
//			Thread.sleep(5000);
//			channel.close();
			json.setCode("200");
			json.setMsg("chargerLogout return received");
		} catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("chargerLogin return fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon requestPayByCard(Map<String, String> map,Channel channel) {
		JsonCommon json = new JsonCommon();
		// 解析报文
		map = ev3cAnalysisService.requestPayByCard(map);
		// TODO returnCode  主服务器接口 queryOfflineCard   查询现金卡卡状态  queryIdentityCardByNo  查询身份识别卡状态
		String returnCode = handleCardStateByType(map.get("userCard"));
		map.put("returnCode", returnCode);
		// 封装待发送报文
		String msg = ev3cEncapsulationService.requestPayByCardReturn(map);
		try {
			sendMsg.sendAsync(msg, map.get("chargerId"));
			json.setCode("200");
			json.setMsg("requestPayByCard return received");
		}catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("chargerLogin return fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	
//	看看要不要写业务逻辑
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadHeart(Map<String, String> map,Channel channel) {
		JsonCommon json = new JsonCommon();
		//解析报文
//		map = ev3cAnalysisService.uploadHeart(map.get("data"));
		map = ev3cAnalysisService.uploadHeart(map);
		//封装待发送报文
		String msg = ev3cEncapsulationService.uploadHeartReturn(map);
		try {
//			sendShortClientService.send(msg);
//			sendMsg.send(msg, 0, null);
			sendMsg.sendAsync(msg, map.get("chargerId"));
//			channel.write(msg);
//			Thread.sleep(5000);
//			channel.close();
			json.setCode("200");
			json.setMsg("uploadHeart return received");
		}catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("chargerLogin return fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadChange(Map<String, String> map,Channel channel) {
		JsonCommon json = new JsonCommon();
		//解析报文
//		map = ev3cAnalysisService.uploadChange(map.get("data"));
		map = ev3cAnalysisService.uploadChange(map);
		//数据库操作
//		String status_type = map.get("status_type");
//		String status_value = map.get("status_value");
//		String chargerId = map.get("chargerId");
//		json = chargerUploadService.uploadChange(chargerId,status_type,status_value);
		json = chargerUploadService.uploadChange(map);
		//封装待发送报文
		String msg = ev3cEncapsulationService.uploadChangeReturn(map);
		try {
//			sendShortClientService.send(msg);
//			sendMsg.send(msg, 0, null);
			sendMsg.sendAsync(msg, map.get("chargerId"));
//			channel.write(msg);
//			Thread.sleep(5000);
//			channel.close();
			json.setCode("200");
			json.setMsg("uploadChange return received");
		}catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("chargerLogin return fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadFirmwareStatus(Map<String, String> map,Channel channel) {
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.uploadFirmwareStatus(map);
		//数据库操作  
		json = chargerUploadService.uploadFirmwareStatus(map);
		//封装待发送报文
		String msg = ev3cEncapsulationService.uploadFirmwareStatusReturn(map);
		try {
//			sendShortClientService.send(msg);
//			sendMsg.send(msg, 0, null);
			sendMsg.sendAsync(msg, map.get("chargerId"));
//			channel.write(msg);
//			Thread.sleep(5000);
//			channel.close();
			json.setCode("200");
			json.setMsg("uploadFirmwareStatus return received");
		}catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("chargerLogin return fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBill(Map<String, String> map,Channel channel) throws Exception
	{
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.uploadBill(map);
		//数据库操作
		json = chargerUploadService.uploadBill(map);
//		String jsonString = uploadDataService.uploadBill(map);
//		json = JSON.toJSON(jsonString);
		//封装待发送报文
		String msg = ev3cEncapsulationService.uploadBillReturn(map);
		try {
//			sendShortClientService.send(msg);
//			sendMsg.send(msg, 0, null);
			sendMsg.sendAsync(msg, map.get("chargerId"));
//			channel.write(msg);
//			Thread.sleep(50000);
//			channel.close();
			json.setCode("200");
			json.setMsg("uploadBill return received");
		}catch (Exception e) {
			json.setCode("10303200");
			json.setMsg("chargerLogin return fail sendLongClientService Exception：" +e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadChargeData(Map<String, String> map) {
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.uploadChargeData(map);
		json.setCode("200");
		json.setMsg("uploadChargeData return received");
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBatteryData(Map<String, String> map) {
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.uploadBatteryData(map);
		json.setCode("200");
		json.setMsg("uploadBatteryData return received");
		return json;
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private JsonCommon summonReturnUploadTelemetry(Map<String, String> map) {
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.summonReturnUploadTelemetry(map);
		//数据库操作
		uploadDataService.uploadTelemeter(map);
//		String jsonString = uploadDataService.uploadBill(map);
//		json = JSON.toJSON(jsonString);
		json.setCode("200");
		json.setMsg("uploadBill return received");
		json.setPojo(map);
		return json;
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private JsonCommon summonReturnUploadTelesignal(Map<String, String> map) {
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.summonReturnUploadTelesignal(map);
//		//数据库操作
		uploadDataService.uploadTelesignal(map);
//		String jsonString = uploadDataService.uploadBill(map);
//		json = JSON.toJSON(jsonString);
		json.setCode("200");
		json.setMsg("uploadBill return received");
		json.setPojo(map);
		return json;
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private JsonCommon summonReturnUploadPulse(Map<String, String> map) {
		JsonCommon json = new JsonCommon();
		//解析报文
		map = ev3cAnalysisService.summonReturnUploadPulse(map);
		//数据库操作
		uploadDataService.uploadRemotePulse(map);
//		String jsonString = uploadDataService.uploadBill(map);
//		json = JSON.toJSON(jsonString);
		json.setCode("200");
		json.setMsg("uploadBill return received");
		json.setPojo(map);
		return json;
	}

	@Override
	public String sendAndWait(String msg, long timoutMillisecond) throws RetryFailException, SendMsgTimeOutException {
//		sendMsg.send(msg, 1000*60, ev3cSendCallBack);
		return null;
//		return sendMsg.sendAndWait(msg, timoutMillisecond);
	}

	@Override
	public MessageFuture sendNoWait(String msg, String chargerid) throws RetryFailException, CreateConnectionFailException, DuplicateInstructionException
	{
		log.debug(this.toString());
		return sendMsg.sendAsync(msg, chargerid);
	}
	@Override
	public JsonCommon receive(String data, Channel c) {
		
		return null;
	}
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void offlineCharger(String chargerId) {
//		String chargerId = map.get("chargerId");
		log.info("reset charger state :"+ chargerId);
		omsChargerDao.exec("update oms_charger_state_alternate set online_status = 0 where charger_id ='"+chargerId +"'");
		omsChargerDao.exec("update oms_charger_state_direct set online_status = 0  where charger_id ='"+chargerId +"'");
//		omsChargerDao.exec("update oms_charger set forward_srv_id = null  where charger_id = '"+chargerId +"'");
	}
	
	/**
	 * 刷卡请求:通过卡的类型来处理卡状态
	 * @param userCard
	 * @return 0x00:卡号有效, 0x01:卡号无效, 0x02:余额不足, 0x03:卡号被冻结, 0x04:操作被拒绝
	 */
	public String handleCardStateByType(String userCard) {
		String returnCode = "00"; // 0x00:卡号有效, 0x01:卡号无效, 0x02:余额不足, 0x03:卡号被冻结, 0x04:操作被拒绝
		String cardType= CardUtils.generateCardType(userCard);
		int cardState = 0; // 0:未激活, 1:激活, 2:冻结, 3:挂失, 4:注销
		if (cardType.equals(OmsConstant.CardTypeEnum.Cash)) { // 现金卡
			MasterQueryOfflineCardVO.MasterQueryOfflineCardParamVO offlineCardParam = new MasterQueryOfflineCardVO.MasterQueryOfflineCardParamVO();
			offlineCardParam.setCardNo(userCard);
			//MasterQueryOfflineCardVO.MasterQueryOfflineCardRetVO result = systemMasterServerRpcClient.queryOfflineCard(offlineCardParam);
			MasterQueryOfflineCardVO.MasterQueryOfflineCardRetVO result = null;
			if (result == null || result.getIsSuccess() != 1) {
				return "04";
			}
			cardState = result.getCardState();
		} else if (cardType.equals(OmsConstant.CardTypeEnum.Identity)) { // 身份识别卡
			MasterQueryIdentityCardVO.MasterQueryIdentityCardParamVO identityCardParam = new MasterQueryIdentityCardVO.MasterQueryIdentityCardParamVO();
			identityCardParam.setCardNo(userCard);
			//MasterQueryIdentityCardVO.MasterQueryIdentityCardRetVO result = systemMasterServerRpcClient.queryIdentityCardByNo(identityCardParam);
			MasterQueryIdentityCardVO.MasterQueryIdentityCardRetVO  result = null;
			if (result == null || result.getIsSuccess() != 1) {
				return "04";
			}
			cardState = result.getCardState();
		} else {
			return "04";
		}
		
		switch (cardState) {
		case 0: // 0:未激活
			returnCode = "01"; // 0x01:卡号无效
			break;
		case 1: // 1:激活
			returnCode = "00"; // 0x00:卡号有效
			break;
		case 2: // 2:冻结
			returnCode = "02"; // 0x01:卡号冻结
			break;
		case 3: // 3:挂失
			returnCode = "01"; // 0x01:卡号无效
			break;
		case 4: // 4:注销
			returnCode = "01"; // 0x01:卡号无效
			break;
		default: // 1:激活
			returnCode = "00"; // 0x00:卡号有效
			break;
		}
		
		return returnCode;
	}
}
